/*
 * bitstore.cpp
 *
 *  Created on: 17/09/2012
 *      Author: peter
 */

#include "bitstore.h"



BitStore::BitStore()
{
	outbuf = 0;
	inbuf = 0;
	outpos = 7;
	inpos = -1;
	filemod = ios::app;
}

BitStore::~BitStore()
{
	if (datafile.is_open()) {
		datafile.close();
	}
}

void BitStore::open(const string name, std::ios::openmode m)
{
	filemod = m;
	assert(filemod==ios::in||filemod==ios::out);
	datafile.open(name.c_str(), ios::binary|filemod);
}

void BitStore::close()
{
	datafile.close();
}

void BitStore::out(uint64_t buf, short len)
{
	assert(len >= 0);
	assert(datafile.is_open());
	while (len > 0) {
		putbit( (buf & (1 << --len)) != 0 );
	}
}

// dette er inconsistent. len betyder ikke det samme
void BitStore::out(uint8_t *buf, short len)
{
	for (short i=0; i<len; i++) {
		out(buf[i], 8);
	};
}

uint64_t BitStore::in(short int len)
{
	uint64_t result = 0;
	assert(len<=64 && len>=0);
	while (len > 0) {
		result |= getbit() << --len;
	}
	return result;
}

void BitStore::putbit(bool bit)
{
	outbuf |= (bit << outpos--);
	if (outpos < 0) {
		datafile.write(&outbuf, 1);
		outpos = 7;
		outbuf = 0;
	}
}

bool BitStore::getbit()
{
	if (inpos < 0) {
		datafile.read(&inbuf, 1);
		inpos = 7;
	}
	return inbuf & (1 << inpos--);
}

